'''
Author: SlytherinGe
LastEditTime: 2021-09-01 20:07:34
'''
import xml.etree.ElementTree as ET
import os
 
 
# 批量修改整个文件夹所有的xml文件
def change_all_xml(xml_path):
    filelist = os.listdir(xml_path)
    l = len(filelist)
    i = 0
    # 打开xml文档
    for xmlfile in filelist:
        doc = ET.parse(xml_path + xmlfile)
        root = doc.getroot()
        for obj in root.findall('object'):
        # 找到object标签
            sub2 = obj.find('polygon')    # 找到Difficult标签
            if sub2 != None:
                sub2.tag = 'bndbox'		# 将Difficult标签的tag首字母小写
        doc.write(xml_path + xmlfile)  # 保存修改
        i += 1
        print('{}/{}'.format(i,l))
 
# 修改某个特定的xml文件
def change_one_xml(xml_path):          # 输入的是这个xml文件的全路径
    # 打开xml文档
    doc = ET.parse(xml_path)
    root = doc.getroot()
    sub1 = root.find('object')       # 找到filename标签，
    sub2 = sub1.find('Difficult')          # 修改标签内容
    sub2.tag = 'difficult'
    doc.write(xml_path)  # 保存修改
    print('----------done--------')

def find_flawed_anno(anno_root):
    xml_files = os.listdir(anno_root)
    for f in xml_files:
        doc = ET.parse(os.path.join(anno_root, f))
        root = doc.getroot()
        size = root.find('size')
        if size == None:
            print(f)


 
# xml_root = 'Annotations/' 
# change_all_xml(xml_root)     # xml文件总路径
# #xml_path = r'Annotations/Gao_ship_hh_02016082544040302.xml'
# #change_one_xml(xml_path)

if __name__ == '__main__':
    change_all_xml('/media/gejunyao/Disk1/Datasets/SSDD/VOC2012/annotations_r/')